//
//  FNMockEnterWindow.m
//  MockServer
//
//  Created by caoyq on 2021/2/9.
//

#import "FNMockEnterWindow.h"
#import "FNMockConfigViewController.h"
#import <objc/runtime.h>

static int _DebugWindowKey;

static inline BOOL fn_isIphoneX() {
    if (@available(iOS 11.0, *)) {
        return [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom > 0;
    }
    return false;
}

@interface FNMockEnterWindow ()
{
    CGFloat _topDis;
    CGFloat _bottomDis;
    CGFloat _leftSpace;
}
 
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSValue *pointInSelf;

@end

@implementation FNMockEnterWindow

#pragma mark - public

+ (void)show {
    FNMockEnterWindow *debugWindow = [[FNMockEnterWindow alloc] init];
    // 强引用，避免提前释放了
    objc_setAssociatedObject([UIApplication sharedApplication].delegate, &_DebugWindowKey,
                             debugWindow, OBJC_ASSOCIATION_RETAIN);
}

#pragma mark - Init

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initWindow];
        [self addTitleLabel];
        [self addTapGesture];
    }
    return self;
}

- (void)initWindow {
    _leftSpace = 10;
    _topDis = fn_isIphoneX() ? 44 : 20;
    _bottomDis = fn_isIphoneX() ? 34 : 10;
    
    CGRect screenFrame = [UIScreen mainScreen].bounds;
    float width = 40;
    float height = 20;
    self.frame = CGRectMake(screenFrame.size.width - width - _leftSpace, _topDis, width, height);
    self.backgroundColor = [UIColor clearColor];
    self.rootViewController = [UIViewController new];
    
    self.windowLevel = UIWindowLevelAlert;
    self.clipsToBounds = YES;
    self.layer.cornerRadius = 5;
    [self makeKeyAndVisible];
}

- (void)addTitleLabel {
    _titleLabel = [[UILabel alloc] initWithFrame:self.bounds];
    _titleLabel.font = [UIFont systemFontOfSize:10];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.backgroundColor = [UIColor blueColor];
    _titleLabel.text = @"Mock";
    [self addSubview:_titleLabel];
}

- (void)addTapGesture {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self addGestureRecognizer:tap];
}

#pragma mark - action

- (void)tapAction {
    // 保证主 window 在展示中
    UIWindow *currentKeyWindow = [UIApplication sharedApplication].delegate.window;
    [currentKeyWindow makeKeyAndVisible];
    
    FNMockConfigViewController *mockVc = [[FNMockConfigViewController alloc] init];
    UIViewController *topVc = [self getTopViewController];
    // 避免多次打开
    if ([topVc isKindOfClass:[mockVc class]]) {
        return;
    }
    if (topVc.navigationController) {
        [topVc.navigationController pushViewController:mockVc animated:YES];
    }else {
        [topVc presentViewController:mockVc animated:YES completion:nil];
    }
}

#pragma mark - private

/// 获取当前窗口最顶层的控制器
- (UIViewController *)getTopViewController {
    UIViewController *topVc = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([topVc isKindOfClass:[UITabBarController class]]) {
        topVc = ((UITabBarController *)topVc).selectedViewController;
    }
    NSArray *vcs = nil;
    if ([topVc isKindOfClass:[UINavigationController class]]) {
        vcs = ((UINavigationController *)topVc).viewControllers;
    }else {
        vcs = topVc.navigationController.viewControllers;
    }
    return vcs ? vcs.lastObject : topVc;
}

#pragma mark - touchs

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    self.pointInSelf = nil;
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesCancelled:touches withEvent:event];
    self.pointInSelf = nil;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];
    
    // 选正确的 window 作参考
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    CGPoint pointInWindow = [[touches anyObject] locationInView:window];
    if (!self.pointInSelf) {
        self.pointInSelf = [NSValue valueWithCGPoint:[[touches anyObject] locationInView:self]];
    }
    // 保证拖动点就是触摸点
    CGFloat x = pointInWindow.x - self.pointInSelf.CGPointValue.x;
    CGFloat y = pointInWindow.y - self.pointInSelf.CGPointValue.y;

    CGRect screenFrame = self.frame;

    CGFloat minY = _topDis;
    CGFloat maxY = [UIScreen mainScreen].bounds.size.height - screenFrame.size.height - _bottomDis;
    CGFloat dynamicY = MIN(maxY, MAX(minY, y));

    CGFloat minX = _leftSpace;
    CGFloat maxX = [UIScreen mainScreen].bounds.size.width - screenFrame.size.width - minX;
    CGFloat dynamicX = MIN(maxX, MAX(minX, x));

    screenFrame.origin = CGPointMake(dynamicX, dynamicY);
    self.frame = screenFrame;
}

@end
